package com.fms.data.messaging;

import java.io.File;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.AuthenticationFailedException;
import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import com.fms.data.messaging.auth.EmailAuthentication;
import com.fms.data.messaging.exceptions.EmailException;
import com.fms.model.domain.FlowSheet;
import com.fms.model.messaging.IMessager;
import com.fms.model.messaging.auth.IAuthentication;
import com.fms.model.messaging.domain.DraftMessage;

public class FlowSheetEmailer implements IMessager
{
	
	private Properties props;
	private IAuthentication	auth;
	private boolean	debug;
	
	
	public FlowSheetEmailer(Properties _emailProperties, IAuthentication _auth, boolean _debug)
	{
		props = _emailProperties;
		auth = _auth;
		this.debug = _debug;
	}
		
	public void send(DraftMessage message) throws EmailException
	{
		try
		{ 
			if(auth.request())
			{
				Session session = Session.getInstance(props, new EmailAuthentication(auth));
				session.setDebug(debug);
				throwIfFileDoesNotExist(message.getSheet());		
				
				if(message.getFrom() == null || message.getFrom().length() == 0)
				{
					message.setFrom(auth.getUser());
				}
				
				MimeMessage mime = new MimeMessage(session);
				mime.setFrom(new InternetAddress(message.getFrom()));
				for( int i = 0; i < message.getTo().size(); i++)
				{
					mime.addRecipient(Message.RecipientType.TO, new InternetAddress(message.getTo().get(i)));
				}
				mime.setSubject(message.getSubject());
				
				MimeMultipart body = new MimeMultipart();
	
				MimeBodyPart bodyText = new MimeBodyPart();
				bodyText.setText(message.getMessage());
				body.addBodyPart(bodyText);
	
				MimeBodyPart attachment = new MimeBodyPart();
				File f = new File(message.getSheet().getFileName());
				DataSource fileSource = new FileDataSource(f.getAbsolutePath());
				attachment.setDataHandler(new DataHandler(fileSource));
				attachment.setFileName(f.getName());
	
				body.addBodyPart(attachment);
				mime.setContent(body);
				 
		        Transport.send(mime);
			}
	        auth.purge();
	        
       
		}		
		catch(Exception e)
		{
			auth.purge();
			if(e.getClass().equals(AuthenticationFailedException.class))
			{
				throw new EmailException("User name and password were incorrect.", e.getCause());
			}
			throw new EmailException(e.getMessage(), e.getCause());
		}
	}
	
//	public SentMessage[] findSentMail() throws SentItemsException
//	{
//		
//		ArrayList<SentMessage> sentMessages = new ArrayList<SentMessage>();
//		
//		try 
//		{
//
//			Message messages[] = this.getSentMessages();
//			
//			for(Message message:messages) 
//			{
//				String subject = "";
//				String text = "";
//				String file = "";
//				
//				if(message.getSubject() != null)
//				{
//					subject = message.getSubject();
//				}
//				if(message.getContent().getClass().equals(MimeMultipart.class))
//				{
//					MimeMultipart part = (MimeMultipart) message.getContent();
//					
//					//BodyPart textPart = findByType(part, "TEXT/PLAIN");
//					BodyPart filePart = findByType(part, "OCTET-STREAM");
//								
//					if(part.getCount() > 0)
//					{
//						if(((MimeMultipart)part.getBodyPart(0).getContent())
//								.getBodyPart(0).getContent().getClass().equals(String.class))
//						{
//							text = (String)((MimeMultipart)part.getBodyPart(0).getContent())
//											.getBodyPart(0).getContent();						
//						}
//					}
//						
//					if( filePart != null)
//					{
//						file = filePart.getFileName();
//					}
//					else
//					{
//						file = "";
//					}
//					
//					
//				}	
//				sentMessages.add(new SentMessage(subject, text, file));
//			}
//		}
//		catch (NoSuchProviderException e) 
//		{
//			throw new SentItemsException(e.getMessage());
//		}
//		catch (MessagingException e) 
//		{
//			if(e.getMessage().contains("[ALERT] Invalid credentials (Failure)"))
//			{
//				throw new SentItemsException("Username and password incorrect.");
//			}
//			
//			throw new SentItemsException(e.getMessage());
//		} 
//		catch (IOException e)
//		{
//			throw new SentItemsException(e.getMessage());
//		} 
//		catch (Exception e)
//		{
//			// TODO Auto-generated catch block
//			e.printStackTrace();
//		}
//		
//		SentMessage[] messages = new SentMessage[sentMessages.size()];
//		
//		messages = sentMessages.toArray(messages);
//		return messages;
//	}
//	
//	
//	
//	private Message[] getSentMessages() throws Exception
//	{
//		
//		Session session = Session.getDefaultInstance(props, null);
//		Store store = session.getStore(props.getProperty("emailer.store"));
//		store.connect(props.getProperty("emailer.server"), 
//					  props.getProperty("emailer.user"), 
//					  props.getProperty("emailer.password"));
//
//
//		
//		Folder inbox = store.getFolder(props.getProperty("emailer.folder.sent"));
//		inbox.open(Folder.READ_ONLY);
//		
//		Message[] messages = inbox.getMessages();
//		return messages;
//		
//	}

	private void throwIfFileDoesNotExist(FlowSheet _sheet) throws Exception
	{
		File existsCheck = new File(_sheet.getFileName());
		if(!existsCheck.exists())
		{

			throw new Exception(existsCheck.getName() + " was not found.");
		}
	}
	
//	private BodyPart findByType(MimeMultipart part, String type) throws MessagingException, IOException
//	{
//		
//		for( int i = 0; i < part.getCount(); i++)
//		{			
//			if(part.getBodyPart(i).getContentType().contains(type))
//			{
//				return part.getBodyPart(i);
//			}
//			
//			if(part.getBodyPart(i).getClass().equals(Multipart.class))
//			{
//				MimeMultipart newPart = (MimeMultipart)part.getBodyPart(i).getContent();
//			
//				if(newPart != null)
//				{
//					BodyPart result = findByType(newPart, type);
//					if(result != null)
//					{
//						return result;
//					}
//				}
//			}
//		}
//		return null;
//	}
}
